package com.apes.scm.masterdata.frame.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.frame.model.Organization;
import com.apes.scm.masterdata.frame.repository.OrganizationRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：组织信息
 *
 * @author HuJianlin
 * @create 2018-03-17 17:35
 */
@Service("organizationService")
public class OrganizationService extends DomainService {
    @Autowired
    public OrganizationRepository organizationRepository;
    @Autowired
    public PartyRoleRepository partyRoleRepository;
    
    public Organization save(SimpleRequest request) {
        Organization organization = request.getO(Organization.class);
        return organizationRepository.saveAndFlush(organization);
    }

    public List<Organization> findAll(SimpleRequest request) {
        return  organizationRepository.findAll();
    }



    public Organization update(SimpleRequest request) {
        Organization organization = request.getO(Organization.class);
        return organizationRepository.save(organization);
    }

    public String delete(SimpleRequest request) throws Exception  {

        String id = request.get("id");
        long versions = (Long) request.get("version");

        Organization organization = organizationRepository.findOne(id);
        if (organization == null) throw new RuntimeException("部门【" + id + "】在系统中不存在。");
        if (organization.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        organizationRepository.delete(organization);

        return "删除成功";


    }

    public Page<Organization> findAllPage(SimpleRequest request){
        List<Map> filters = request.get("condition");
        return organizationRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    public Page<Organization> find(SimpleRequest request) throws Exception{
        return organizationRepository.find( request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }

    public Organization findOne(String id) {
        return organizationRepository.findOne(id);
    }


















}
